import request from '../utils/request';

// 认证相关API
export const authApi = {
  // 学生登录
  studentLogin: (data) => {
    const loginData = {
      email: data.email,
      password: data.password,
      privacy_policy_agreed: data.privacy_policy_agreed
    };
    return request.post('/api/student/login', loginData);
  },
  
  // 企业登录
  enterpriseLogin: (data) => {
    const loginData = {
      email: data.email,
      password: data.password,
      privacy_policy_agreed: data.privacy_policy_agreed
    };
    return request.post('/api/enterprise/login', loginData);
  },
  
  // 学生注册
  studentRegister: (data) => request.post('/api/student/register', data),
  
  // 企业注册
  enterpriseRegister: (data) => request.post('/api/enterprise/register', data),
  
  // 发送验证码
  sendCode: (data) => request.post('/api/user/sendCode', data),
  
  // 邮箱验证
  verifyEmail: (token) => request.post('/api/user/verify-email', { token }),
  
  // 忘记密码
  forgotPassword: (data) => request.post('/api/user/forgot-password', data),
  
  // 重置密码
  resetPassword: (data) => request.post('/api/api/auth/reset-password', data),
  
  // 登出
  logout: () => {
    const userType = localStorage.getItem('user_type');
    const endpoint = userType === 'enterprise' ? '/api/enterprise/logout' : '/api/student/logout';
    return request.post(endpoint);
  }
};

// 用户相关API
export const userApi = {
  // 登录 - 简化为只传递三个参数
  login: (data) => {
    // 简化的登录数据，只包含三个必需参数
    const loginData = {
      email: data.email,
      password: data.password,
      privacy_policy_agreed: data.privacy_policy_agreed
    };
    
    // 根据用户类型调用不同的登录接口
    if (data.user_type === 'student') {
      return request.post('/api/student/login', loginData);
    } else if (data.user_type === 'enterprise') {
      return request.post('/api/enterprise/login', loginData);
    } else {
      return request.post('/api/student/login', loginData); // 默认学生登录
    }
  },
  
  // 注册
  register: (data) => request.post('/api/auth/register', data),
  
  // 登出
  logout: () => {
    const user_type = localStorage.getItem('user_type');
    if (user_type === 'student') {
      return request.post('/api/student/logout');
    } else if (user_type === 'enterprise') {
      return request.post('/api/enterprise/logout');
    } else {
      return request.post('/api/student/logout');
    }
  },
  
  // 刷新Token
  refreshToken: (refreshToken) => request.post('/api/api/auth/refresh-token', { refresh_token: refreshToken }),
  // 学生注册 - 新的接口规范
  registerStudent: (data) => request.post('/api/student/register', data),
  // 企业注册 - 新的接口规范
  registerEnterprise: (data) => request.post('/api/enterprise/register', data),
  // 验证邮箱
  verifyEmail: (token) => request.post('/api/user/verify-email', { token }),
  
  // 重新发送验证邮件
  resendVerificationEmail: (data) => request.post('/api/user/sendCode', data),
  
  // 忘记密码 - 发送重置链接
  forgotPassword: (data) => {
    return request.post('/api/user/forgot-password', data);
  },
  
  // 重置密码
  resetPassword: (data) => request.post('/api/api/auth/reset-password', data),
  
  // 获取用户信息
  getUserInfo: () => request.get('/api/user/profile'),
  
  // 更新用户信息
  updateUserInfo: (data) => request.put('/api/user/profile', data),
  
  // 修改密码
  changePassword: (data) => request.post('/api/api/user/change-password', data),
  
  // 检查邮箱是否已注册
  checkEmail: (email) => request.get('/api/api/auth/check-email', { params: { email } }),
  
  // 获取登录历史
  getLoginHistory: () => request.get('/api/api/user/login-history'),
  
  // 获取账户状态
  getAccountStatus: () => request.get('/api/api/user/account-status'),
  
  // 上传头像
  uploadAvatar: (file) => {
    const formData = new FormData();
    formData.append('avatar', file);
    return request.post('/api/user/avatar', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
  },

  // 邮箱激活
  verifyEmail: (token) => request.get(`/api/verify-email?token=${token}`),

  // 发送激活邮件
  sendActivation: (data) => request.post('/api/user/sendCode', data),

  // 发送激活邮件（无需认证版本）
  sendActivationNoAuth: (data) => {
    // 使用request实例，但不添加认证头
    return request.post('/api/user/sendCode', data, {
      headers: { 'Content-Type': 'application/json' }
    });
  },

  // 企业认证相关API
  enterpriseCertification: {
    // 获取认证状态
    getStatus: () => request.get('/api/enterprise/certification/status'),
    
    // 提交认证申请
    submit: (data) => request.post('/api/enterprise/certification/submit', data),
    
    // 更新认证信息
    update: (data) => request.put('/api/enterprise/certification/update', data),
    
    // 重新提交认证
    resubmit: (data) => request.post('/api/enterprise/certification/resubmit', data),
    
    // 获取认证历史
    getHistory: () => request.get('/api/enterprise/certification/history'),
    
    // 上传认证文件
    uploadFile: (file, type) => {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('type', type);
      return request.post('/api/enterprise/certification/upload', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      });
    }
  },

  // 企业信息相关API
  enterpriseInfo: {
    // 获取企业信息
    getInfo: () => request.get('/api/enterprise/info'),
    
    // 更新企业信息
    updateInfo: (data) => request.put('/api/enterprise/info', data),
    
    // 上传企业LOGO
    uploadLogo: (file) => {
      const formData = new FormData();
      formData.append('logo', file);
      return request.post('/api/enterprise/logo', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      });
    }
  },

  // 检测邮箱激活状态
  checkActivationStatus: (data) => request.get('/api/user/check-activation-status', { params: data }),

  // 学生激活注册接口
  activateRegister: (data) => request.post('/api/user/sendCode', data),

  // 检查邮箱状态 - 新接口
  checkEmailStatus: (data) => request.post('/api/codeuser/user/check-email-status', data)
};

// 企业相关API
export const enterpriseApi = {
  // 企业认证
  certification: (data) => request.post('/api/enterprise/certification', data),
  
  // 发布需求
  createDemand: (data) => request.post('/api/enterprise/demands', data),
  
  // 获取需求列表
  getDemands: (params) => request.get('/api/enterprise/demands', { params }),
  
  // 更新需求
  updateDemand: (id, data) => request.put(`/api/enterprise/demands/${id}`, data),
  
  // 获取申请列表
  getApplications: (params) => request.get('/api/api/v1/enterprise/application/my-requests', { params }),
  
  // 处理申请
  handleApplication: (id, action) => request.put(`/api/api/v1/enterprise/application/${id}/handle`, { action }),
  
  // 获取国籍列表 - 企业端专用API
  getNationalities: () => request.get('/api/api/v1/enterprise/nationalities')
};

// 需求管理相关API
export const demandApi = {
  // 获取表单配置
  getFormConfig: () => request.get('/api/api/v1/enterprise/demands/form-config'),
  
  // 获取国家和城市多级联列表
  getLocations: () => request.get('/api/api/v1/enterprise/demands/locations'),
  
  // 获取国籍列表
  getCountries: () => request.get('/api/api/v1/enterprise/demands/countries'),
  
  // 获取城市列表
  getCities: (countryId) => request.get(`/api/api/v1/enterprise/demands/cities`, { 
    params: { countryId } 
  }),
  
  // 发布需求
  publishDemand: (data) => request.post('/api/api/v1/enterprise/demands/publish', data),
  
  // 获取企业需求列表（企业端管理用）
  getDemandList: (params) => request.get('/api/api/v1/enterprise/demand/manage/list', { params }),
  
  // 编辑需求
  editDemand: (demandId, data) => request.put(`/api/api/v1/enterprise/demand/manage/edit/${demandId}`, data),
  
  // 获取消息列表
  getMessages: (params) => request.get('/api/api/v1/enterprise/certification/messages', { params }),
  
  // 获取所有已发布需求列表（需求库展示用）
  getAllPublishedDemands: (params) => request.get('/api/api/v1/enterprise/demand/manage/all', { 
    params,
    headers: {
      'X-User-Type': 'student',
      'X-Request-Source': 'public-view'
    }
  })
};

// 企业撮合申请相关API
export const applicationApi = {
  // 企业查看撮合请求列表
  getMyRequests: (params) => request.get('/api/api/v1/enterprise/application/my-requests', { params }),
  
  // 企业请求撮合学生
  requestMatch: (studentId) => request.post('/api/api/v1/enterprise/application/request-match', { studentId })
};

// 学生相关API
export const studentApi = {
  // 获取需求列表 - 使用企业需求管理接口（学生访问）
  getDemands: (params) => request.get('/api/api/v1/enterprise/demand/manage/all', { 
    params,
    headers: {
      'X-User-Type': 'student',
      'X-Request-Source': 'public-view'
    }
  }),
  
  // 申请职位
  applyJob: (demandId) => request.post(`/api/api/v1/student/demands/${demandId}/apply`),
  
  // 获取申请记录
  getApplications: (params) => request.get('/api/api/v1/student/application/records', { params }),
  
  // 取消申请
  cancelApplication: (id) => request.delete(`/api/student/applications/${id}`),
  
  // 简历相关API
  // 获取完整简历信息
  getResume: () => request.get('/api/api/v1/student/resume'),
  
  // 创建/更新完整简历
  createResume: (data) => request.post('/api/api/v1/student/resume', data),
  
  // 更新简历信息
  updateResume: (data) => request.put('/api/api/v1/student/resume', data),
  
  // 获取简历状态
  getResumeStatus: () => request.get('/api/api/v1/student/resume/status'),
  
  // 提交简历审核
  submitResume: () => request.post('/api/api/v1/student/resume/submit'),
  
  // 删除简历
  deleteResume: () => request.delete('/api/api/v1/student/resume'),
  
  // 获取国籍列表
  getNationalities: () => request.get('/api/api/v1/enterprise/demands/countries')
};

// 人才库相关API
export const talentApi = {
  // 获取所有人才列表（支持分页）
  getAllTalents: (page = 1, size = 10) => request.get('/api/api/v1/enterprise/talent/list', { 
    params: { page, size } 
  }),
  
  // 筛选人才
  filterTalents: (params) => request.get('/api/api/v1/enterprise/talent/filter', { params }),
  
  // 搜索人才
  searchTalents: (keyword, page = 1, size = 10) => request.get('/api/api/v1/enterprise/talent/search', { 
    params: { keyword, page, size } 
  }),
  
  // 获取人才详情
  getTalentDetail: (id) => request.get(`/api/api/v1/enterprise/talent/${id}`),
  
  // 获取筛选选项
  getFilterOptions: () => request.get('/api/api/v1/enterprise/talent/filter-options'),
  
  // 获取国家列表
  getCountries: () => request.get('/api/api/v1/enterprise/demands/countries'),
  
  // 联系人才
  contactTalent: (studentId, message) => request.post('/api/api/v1/enterprise/talent/contact', {
    student_id: studentId,
    message: message
  }),
  
  // 申请撮合
  requestMatch: (studentId) => request.post('/api/api/v1/enterprise/application/request-match', {
    studentId: studentId
  })
};

// 消息相关API
export const messageApi = {
  // 获取消息列表
  getMessages: (params) => request.get('/api/messages', { params }),
  
  // 发送消息
  sendMessage: (data) => request.post('/api/messages', data),
  
  // 标记消息为已读
  markAsRead: (id) => request.put(`/api/messages/${id}/read`),
  
  // 删除消息
  deleteMessage: (id) => request.delete(`/api/messages/${id}`)
};

// 文件上传API
export const uploadApi = {
  // 上传文件
  uploadFile: (file, type = 'general') => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('type', type);
    return request.post('/api/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
  }
};

// 协议相关API
export const policyApi = {
  // 获取学生端政策列表
  getStudentPolicyList: () => request.get('/api/student/policy/list'),
  
  // 获取企业端政策列表
  getEnterprisePolicyList: () => request.get('/api/enterprise/policy/list'),
  
  // 获取学生端最新政策
  getStudentLatestPolicy: () => request.get('/api/student/policy/latest'),
  
  // 获取企业端最新政策
  getEnterpriseLatestPolicy: () => request.get('/api/enterprise/policy/latest'),
  
  // 根据类型获取学生端特定政策
  getStudentPolicyByType: (policyType) => request.get(`/api/student/policy/${policyType}`),
  
  // 根据类型获取企业端特定政策
  getEnterprisePolicyByType: (policyType) => request.get(`/api/enterprise/policy/${policyType}`),
  
  // 记录用户同意协议
  recordAgreement: (data) => request.post('/api/student/policy/agreement/record', data),
  
  // 获取用户协议同意历史
  getAgreementHistory: (userId, userType) => request.get(`/api/api/policy/agreement/history/${userType}/${userId}`),
  
  // 检查用户是否需要重新同意协议
  checkAgreementStatus: (userId, userType) => request.get(`/api/api/policy/agreement/status/${userType}/${userId}`),

  // 获取用户协议（新接口）
  getUserAgreement: () => request.get('/api/policy/agreement'),

  // 获取隐私政策（新接口）
  getPrivacyPolicy: () => request.get('/api/policy/privacy')
};

// 系统相关API
export const systemApi = {
  // 获取系统配置
  getConfig: () => request.get('/api/api/system/config'),
  
  // 获取多语言配置
  getLanguages: () => request.get('/api/api/system/languages'),
  
  // 获取验证码
  getCaptcha: () => request.get('/api/api/system/captcha'),
  
  // 验证验证码
  verifyCaptcha: (data) => request.post('/api/api/system/verify-captcha', data)
};
